import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:steam_app/provider/home_provider.dart';
import 'package:steam_app/view/game_detail/game_detail_page.dart';
import 'package:steam_app/view/security/token_page.dart';
import 'package:steam_app/view/user/user_page.dart';
import 'package:steam_app/view/wishlist/wishlist_page.dart';

import 'provider/user_provider.dart';
import 'provider/library_provider.dart';
import 'provider/wishlist_provider.dart';
import 'package:steam_app/view/login/login_page.dart';
import 'package:steam_app/view/login/register_page.dart';
import 'package:steam_app/view/home/home_page.dart';

void main() {
  runApp(
    // 使用 MultiProvider 将所有 Provider 注册到 Widget 树的顶层
    MultiProvider(
      providers: [
        ChangeNotifierProvider(create: (_) => UserProvider()),
        ChangeNotifierProvider(create: (_) => HomeProvider()),
        // ChangeNotifierProxyProvider可以让一个 Provider 依赖另一个
        ChangeNotifierProxyProvider<UserProvider, WishlistProvider>(
          create: (_) => WishlistProvider(),
          update: (context, userProvider, wishlistProvider) {
            final userId = userProvider.currentUser?.id;
            if (userId != null) {
              // 自动获取该用户的数据
              wishlistProvider!.fetchWishlist(userId);
            }
            return wishlistProvider!;
          },
        ),
        ChangeNotifierProxyProvider<UserProvider, LibraryProvider>(
          create: (_) => LibraryProvider(),
          update: (context, userProvider, libraryProvider) {
            final userId = userProvider.currentUser?.id;
            if (userId != null) {
              libraryProvider!.fetchLibrary(userId);
            }
            return libraryProvider!;
          },
        ),
      ],
      child: const MyApp(),
    ),
  );
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Steam Flutter',
      debugShowCheckedModeBanner: false,
      theme: ThemeData.dark(),
      initialRoute: '/login',
      routes: {
        '/login': (context) => const LoginPage(),
        '/register': (context) => const RegisterPage(),
        '/home': (context) => const HomePage(),
        '/user': (context) => const UserPage(),
        '/game_detail': (context) => const GameDetailPage(),
        '/token': (context) => const TokenPage(),
      },
    );
  }
}
